package com.oa.modules.approvalsec1.controller;

import java.math.BigDecimal;
import java.util.*;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.oa.common.utils.AppUtils;
import com.oa.modules.approvalsec1.entity.BiddEntity;
import com.oa.modules.approvalsec1.entity.BiddProjectEntity;
import com.oa.modules.approvalsec1.service.BiddProjectService;
import com.oa.modules.approvalsec1.service.BiddService;
import com.oa.modules.approvalsec1.service.MattersService;
import com.oa.modules.sys.controller.AbstractController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import com.oa.common.utils.PageUtils;
import com.oa.common.utils.R;

/**
 * 事项
 *
 * @author Hankaicheng
 * @email 785297226@qq.com
 * @date 2022-05-05 15:23:15
 */
@RestController
@RequestMapping("biddproject")
@Api(tags = "事项相关接口")
@Log4j2
public class BiddProjectController extends AbstractController {

    @Autowired
    private BiddProjectService projectService;

    @Autowired
    private BiddService biddService;

    @Autowired
    private MattersService mattersService;


    /**
     * 列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "列表")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = projectService.queryPage(params);
        List<BiddProjectEntity> list = (List<BiddProjectEntity>) page.getList();
        list.forEach(item -> {
            //将服务事项转为字符串形式
            List<String> matters = mattersService.getItemsByIdStr(item.getServiceItems());
            if (StringUtils.isNotBlank(item.getOtherMatter())) {
                matters.add(item.getOtherMatter());
            }
            item.setServiceItems(StringUtils.join(matters, ","));
            //如果是查询竞价结果的话，设置竞价结果
            BiddEntity bidd = null;
            if (params.get("joint") != null && !"".equals(params.get("joint"))) {
                bidd = biddService.getOne(new QueryWrapper<BiddEntity>().eq("project_id", item.getId()).eq("joint", Convert.toInt(params.get("joint"))));
                if (Objects.equals(item.getWinJoint(), Convert.toInt(params.get("joint")))) {
                    item.setResult("已中标");
                } else if (item.getWinJoint() != null) {
                    item.setResult("未中标");
                }
            }
            //委托单位查竞价结果
            if (item.getStatus() == 5) {
                if (item.getWinJoint() != null || item.getWinQiye() != null) {
                    item.setResult("已完结");
                } else {
                    item.setResult("流标");
                }
            }
            //返回当前用户的竞价金额
            if (bidd != null) item.setBidd(bidd.getMoney());
        });
        page.setList(list);
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "信息")
    public R info(@PathVariable("id") String id, @RequestParam Integer jointId, @RequestParam Integer type) {
        BiddProjectEntity project = projectService.getById(id);
        List<String> matters = mattersService.getItemsByIdStr(project.getServiceItems());
        if (StringUtils.isNotBlank(project.getOtherMatter())) {
            matters.add(project.getOtherMatter());
        }
        project.setServiceItems(StringUtils.join(matters, ","));
        //如果查带选取的话，需要在详情里吧带选取的竞价信息展示出来
        List<BiddEntity> bidds = biddService.list(new QueryWrapper<BiddEntity>().eq("project_id", project.getId()));
        //联合体只能看到自己的报价金额,看不到其他联合体的竞价金额
        if (type == 1) {
            bidds.forEach(e -> {
                if (!e.getJoint().equals(jointId)) {
                    e.setMoney(null);
                }
            });
        }
        project.setBidds(bidds);

        //如果状态等于4或者5的话就把最后选取的联合体返回
        if (project.getStatus() == 4 || project.getStatus() == 5) {
            if (project.getWinQiye() != null) {
                BiddEntity bidd = biddService.getOne(new QueryWrapper<BiddEntity>().eq("project_id", project.getId()).eq("institution_id", project.getWinQiye()));
                project.setWin(bidd);
            }
            if (project.getWinJoint() != null) {
                BiddEntity bidd = biddService.getOne(new QueryWrapper<BiddEntity>().eq("project_id", project.getId()).eq("joint", project.getWinJoint()));
                project.setWin(bidd);
            }
        }
        return R.ok().put("project", project);
    }

    /**
     * 信息
     */
    @GetMapping("/aInfo")
    @ApiOperation(value = "信息")
    public R aInfo(@RequestParam String id, @RequestParam Integer jointId, @RequestParam Integer type) {
        BiddProjectEntity project = projectService.getById(id);
        List<String> matters = mattersService.getItemsByIdStr(project.getServiceItems());
        if (StringUtils.isNotBlank(project.getOtherMatter())) {
            matters.add(project.getOtherMatter());
        }
        project.setServiceItems(StringUtils.join(matters, ","));
        //如果查带选取的话，需要在详情里吧带选取的竞价信息展示出来
        List<BiddEntity> bidds = biddService.list(new QueryWrapper<BiddEntity>().eq("project_id", project.getId()));
        //联合体只能看到自己的报价金额,看不到其他联合体的竞价金额
        if (type == 1) {
            bidds.forEach(e -> {
                if (!e.getJoint().equals(jointId)) {
                    e.setMoney(null);
                }
            });
        }
        project.setBidds(bidds);

        //如果状态等于4或者5的话就把最后选取的联合体返回
        if (project.getStatus() == 4 || project.getStatus() == 5) {
            if (project.getWinQiye() != null) {
                BiddEntity bidd = biddService.getOne(new QueryWrapper<BiddEntity>().eq("project_id", project.getId()).eq("institution_id", project.getWinQiye()));
                project.setWin(bidd);
            }
            if (project.getWinJoint() != null) {
                BiddEntity bidd = biddService.getOne(new QueryWrapper<BiddEntity>().eq("project_id", project.getId()).eq("joint", project.getWinJoint()));
                project.setWin(bidd);
            }
        }
        return R.ok().put("project", project);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    @ApiOperation(value = "保存")
    public R save(@RequestBody BiddProjectEntity project) {
        project.setId(AppUtils.getUUID());
        project.setCreateTime(new Date());
        projectService.save(project);
        return R.ok();
    }

    /**
     *修改
     */
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public R update(@RequestBody BiddProjectEntity project) {
        project.setUpdateTime(new Date());
        projectService.updateById(project);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除")
    public R delete(@RequestBody String[] ids) {
        projectService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    @ApiOperation("竞价")
    @PostMapping("/bidd")
    public R bidd(@RequestBody Map<String, Object> params) {
        BiddProjectEntity project = projectService.getById(params.get("projectId").toString());
        project.setMoney((BigDecimal) params.get("money"));
        projectService.updateById(project);
        return R.ok();
    }

    @ApiOperation("选取")
    @PostMapping("/choose")
    public R choose(@RequestBody BiddEntity bidd) {
        if (StringUtils.isNotEmpty(String.valueOf(bidd.getInstitutionId()))) {
            projectService.update(new UpdateWrapper<BiddProjectEntity>().eq("id", bidd.getProjectId()).set("win_qiye", bidd.getInstitutionId()).set("status", 4).set("bidd", bidd.getMoney()));
        }
        if (StringUtils.isNotEmpty(String.valueOf(bidd.getJoint()))) {
            projectService.update(new UpdateWrapper<BiddProjectEntity>().eq("id", bidd.getProjectId()).set("win_joint", bidd.getJoint()).set("status", 4).set("bidd", bidd.getMoney()));
        }
        return R.ok();
    }

    @ApiOperation("评价")
    @PostMapping("/evaluate")
    public R evaluate(@RequestBody BiddProjectEntity project) {
        projectService.update(new UpdateWrapper<BiddProjectEntity>().eq("id", project.getId()).set("status", 5).set("service_quality", project.getServiceQuality()).set("service_attitude", project.getServiceAttitude()).set("service_efficiency", project.getServiceEfficiency()).set("evaluate", project.getEvaluate()));
        return R.ok();
    }

    @GetMapping("/test")
    public R test() {
        BiddProjectEntity projectServiceById = projectService.getById("00a40dd7f3ae41b0b317361e0dd47c2f");
        return R.ok().put("data", projectServiceById);
    }


}
